var-let-const
var, let, and const โ What's the Difference?#
One of the features that came with ES6 is the addition of let and const which can be used for variable declaration. The question now is, what makes them different from var which we've been using?
In this workshop, we'll discuss var, let and const with respect to their scope, use, and hoisting.
Before we start, lets talk a bit about scope in JavaScript (we'll talk more about scope in the next workshop).
JavaScript Scope#
Scope is the accessibility of variables and functions in some particular part of your code during runtime. In other words, scope determines the visibility of variables and other resources in areas of your code. So, scope essentially means where your variables are available for use
Don't worry much about scope now, since it's not our topic for this workshop and we will talk about it more in the next workshop.But, we may come across the word scope in this workshop, so be ready.
Differences between (var, let, const)#
1. var
Before the advent of ES6, var declarations ruled as a King. Let us get to understand var more.
varvariables can be re-declared:
Example (1)
varvariables can be updated:
Example (2)
Hoisting of
var:Hoisting is a JavaScript mechanism where variables declarations are moved to the top of their scope(we'll talk more about scope in the next workshop) before code execution. What this means is that if we do:
Example (3)
...it is interpreted like
Example (4)
So, var variables are hoisted to the top of their scope and initialized with a value of undefined.
2. let
let is preferred for variable declaration now. It's no surprise as it comes as an improvement to the var declarations.
Example (1)
letcan be updated:Like
var,letcan be updated.
Example (2)
letdeclarations are hoisted to the top:Unlike
varwhich is initialized with a value ofundefined, theletkeyword is not initialized. So if you try to useletvariable before declaration, you'll get a Reference Error.
Example (3)
letcan't be re-declared:
Example (4)
3. const
Variables declared with const maintain constant values. const declarations share some similarities with let declarations.
constcannot be updated or re-declared:This means that the value of a variable declared with
constremains the same. It cannot be updated or re-declared. So if we declare a variable withconst, we can neither do:
Example (1)
...nor
Example (2)
Hoisting of
const:Just like
let,constdeclarations are hoisted to the top but are not initialized.
Example (3)
Wrap-up#
varvariables can be updated and re-declared within its scope;letvariables can be updated but not re-declared;constvariables can neither be updated nor re-declared.They are all hoisted to the top of their scope. But while
varvariables are initialized with undefined,letandconstvariables are not initialized.While
varandletcan be declared without being initialized,constmust be initialized during declaration.